import axios from 'axios'
import QS from 'qs'

// timeout
axios.defaults.timeout = 10000
// 允许携带cookie请求
axios.defaults.withCredentials = true

// get token
const getToken = () => {
   const token = getStorage(TOKEN)
   let data = {}
   token && (data.token = token);
   return data
}

// 请求拦截器
axios.interceptors.request.use(config => {
   // get
   if (config.method === "get") {
      config.params = {
         ...getToken(), ...config.params || {},
      }
   }
   // post
   if (config.method === "post") {
      config.data = {
         ...getToken(), ...config.data || {}
      }
      config.data = QS.stringify(config.data)
      //console.log("config", config)
   }
   //console.log("config", config)
   return config
}, error => {
   return Promise.error(error)
})

// 响应拦截器
axios.interceptors.response.use(response => {
      let res = response.data
      let status = response.status

      if (status === 200) {
         let code = res.status || false
         let message = res.message || ""

         if (code === true && message === "ok") {
            return Promise.resolve(res)
         }
         // token 过期, 验证错误, 其它 等等判断
         else {
            return Promise.reject(res)
         }
      } else {
         return Promise.reject(res)
      }
   }, // 服务器状态码不是2xx的情况
   error => {
      if (error.status) {
         // 定义错误码
         if (error.status === 500) {
            console.log('服务器错误')
            return Promise.reject(error.response)
         } else {
            return Promise.reject(error.response)
         }
      }
   })

/**
 * get方法，对应get请求
 * @param url
 * @param params
 * @param isToken
 */
export function get(url, params, isToken = false) {
   return new Promise((resolve, reject) => {
      params = {
         ...params,
      }
      //Object.assign(params || {}, getTokenParam(isToken))
      //console.log("get", url, params, isToken)
      axios.get(url, {
         params,
      }).then(res => {
         //console.log("get then", res)
         if (res) {
            resolve(res)
         } else {
            reject({code: -1, data: null, msg: "none"})
         }
      }).catch(err => {
         //console.log("get catch", err)
         reject(err)
      })
   })
}

/**
 * post方法，对应post请求
 * @param url
 * @param data
 * @param isToken
 */
export function post(url, data, isToken = false) {
   return new Promise((resolve, reject) => {
      // Object.assign(data || {}, getTokenParam(isToken))
      //console.log("post", url, data, isToken)
      axios.post(url, data).then(res => {
         resolve(res)
      }).catch(err => {
         reject(err)
      })
   })
}
